import 'dart:developer';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

/// FileName public_web_view
///
/// @Author lax
/// @Date 2024/3/3
///
/// @Description

class PublicWebView extends StatefulWidget {
  /// 加载工程中的本地文件（例: assets/index.html）
  final String? filePath;

  /// 加载网络地址 （或加载沙盒中的本地文件 使用file://开头）
  final String? urlString;

  /// iOS授权访问目录（file://开头）
  final String? allowingReadAccess;

  /// 事件绑定 key为事件名称 value为回调方法
  final Map<String, JavaScriptHandlerCallback>? javaScriptHandlerMap;

  /// 初始化完成回调
  final Function(InAppWebViewController controller)? onWebViewCreated;

  final Function(InAppWebViewController controller, int progress)?
      onProgressChanged;

  /// 控制台打印消息回调
  final Function(
          InAppWebViewController controller, ConsoleMessage consoleMessage)?
      onConsoleMessage;

  /// 加载结束回调
  final Function(InAppWebViewController controller)? onLoadStop;

  /// 加载失败回调
  final Function(InAppWebViewController controller)? onLoadError;

  final Future<NavigationActionPolicy?> Function(
          InAppWebViewController controller, NavigationAction navigationAction)?
      shouldOverrideUrlLoading;

  final InAppWebViewGroupOptions? initialOptions;

  final bool? cacheEnabled;

  final bool? clearCache;

  final bool? verticalScrollBarEnabled;

  const PublicWebView({
    Key? key,
    this.filePath,
    this.urlString,
    this.allowingReadAccess,
    this.javaScriptHandlerMap,
    this.onWebViewCreated,
    this.onProgressChanged,
    this.onConsoleMessage,
    this.onLoadStop,
    this.onLoadError,
    this.shouldOverrideUrlLoading,
    this.initialOptions,
    this.cacheEnabled,
    this.clearCache,
    this.verticalScrollBarEnabled,
  }) : super(key: key);

  @override
  PublicWebViewState createState() => PublicWebViewState();
}

class PublicWebViewState extends State<PublicWebView> {
  InAppWebViewController? _webViewController;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (await _webViewController?.canGoBack() ?? false) {
          _webViewController?.goBack();
          return false;
        }
        return true;
      },
      child: InAppWebView(
        initialFile: widget.filePath?.split('?').first,
        initialUrlRequest: URLRequest(url: Uri.parse(widget.urlString ?? '')),
        initialOptions: widget.initialOptions ??
            InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                // 允许文件上传
                mediaPlaybackRequiresUserGesture: true,
                allowFileAccessFromFileURLs: true,
                allowUniversalAccessFromFileURLs: true,
                useShouldOverrideUrlLoading: true,
                useOnLoadResource: true,
                transparentBackground: true,
                cacheEnabled: widget.cacheEnabled ?? true,
                clearCache: widget.clearCache ?? false,
                verticalScrollBarEnabled:
                    widget.verticalScrollBarEnabled ?? false,
              ),
              android: AndroidInAppWebViewOptions(
                useHybridComposition: true,
              ),
              ios: IOSInAppWebViewOptions(
                allowsBackForwardNavigationGestures: false,
                allowingReadAccessTo: widget.allowingReadAccess == null
                    ? null
                    : Uri.parse(widget.allowingReadAccess!),
              ),
            ),
        onWebViewCreated: (controller) {
          if (kDebugMode) {
            log('开始加载：${widget.filePath ?? widget.urlString}');
            print('开始加载：${widget.filePath ?? widget.urlString}');
          }
          _webViewController = controller;
          widget.javaScriptHandlerMap?.forEach((key, value) {
            controller.addJavaScriptHandler(
              handlerName: key,
              callback: (args) {
                log('调用自定义JS方法：$key, args=$args');
                return value(args);
              },
            );
          });
          widget.onWebViewCreated?.call(controller);
        },
        onProgressChanged: (controller, progress) {
          widget.onProgressChanged?.call(controller, progress);
        },
        onConsoleMessage: (controller, consoleMessage) {
          if (kDebugMode) {
            log('控制台：$consoleMessage');
            print('控制台：$consoleMessage');
          }
          widget.onConsoleMessage?.call(controller, consoleMessage);
        },
        onLoadStop: (controller, url) {
          if (kDebugMode) {
            log('加载完成：$url');
            print('加载完成：$url');
          }
          widget.onLoadStop?.call(controller);
        },
        onLoadError: (controller, url, code, message) {
          if (kDebugMode) {
            log('加载失败：$url, code = $code, error = $message');
            print('加载失败：$url, code = $code, error = $message');
          }
          widget.onLoadError?.call(controller);
        },
        shouldOverrideUrlLoading: (controller, navigationAction) async {
          if (kDebugMode) {
            log('跳转链接：${navigationAction.request.url}');
            print('跳转链接：${navigationAction.request.url}');
          }
          if (widget.shouldOverrideUrlLoading != null) {
            widget.shouldOverrideUrlLoading?.call(controller, navigationAction);
            return null;
          } else {
            return NavigationActionPolicy.ALLOW;
          }
        },
      ),
    );
  }
}
